<template>


  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.close"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <el-form size="small" ref="formOpsComputerServerRef" :rules="checkRule" :model="submitData" label-width="180px">

      <el-form-item label="父级" prop="parentId">
          <el-input v-if="submitData.parentId === '-1'" value="当前顶级节点，无父级" disabled />
          <el-input v-else v-model.trim="selectComputer.name" disabled />
      </el-form-item>

      <el-form-item label="机器名称(别名)" prop="name">
        <el-input v-model.trim="submitData.name" placeholder="请输入机器名称，用于识记" />
      </el-form-item>

      <el-form-item label="计算机主机名" prop="hostName">
          <el-input v-model.trim="submitData.hostName" />
      </el-form-item>

      <el-form-item label="ip地址" prop="ips">
        <el-input v-model.trim="submitData.ips" placeholder="请输入ip地址，做多支持5个，英文逗号分隔" />
      </el-form-item>

      <el-form-item label="特殊机器" prop="special">
          <el-select v-model="submitData.special" placeholder="请选择" clearable>
              <el-option
                      v-for="item in computerSpecialOpt"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
              </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="使用状态" prop="useStatus">
          <el-radio v-model="submitData.useStatus" :label="1">使用</el-radio>
          <el-radio v-model="submitData.useStatus" :label="9">停用</el-radio>
      </el-form-item>

      <el-form-item label="存放的位置" prop="storageLocation">
          <el-input v-model.trim="submitData.storageLocation" type="textarea" :autosize="{minRows: 2}" />
      </el-form-item>

      <el-form-item label="系统类型" prop="os">
          <el-select v-model="submitData.os" placeholder="请选择" clearable>
              <el-option
                      v-for="item in osOpt"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key">
              </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="系统版本" prop="osVersion">
          <el-input v-model="submitData.osVersion" />
      </el-form-item>

      <el-form-item label="是否重要" prop="linchpin">
          <el-radio v-model="submitData.linchpin" :label="1">重要</el-radio>
          <el-radio v-model="submitData.linchpin" :label="0">非重要</el-radio>
      </el-form-item>

      <el-form-item label="是否虚拟机" prop="vm">
        <el-radio v-model="submitData.vm" :label="1" @change="selectVm('1')">虚拟机</el-radio>
        <el-radio v-model="submitData.vm" :label="0" @change="selectVm('0')">物理机</el-radio>
      </el-form-item>

      <el-form-item label="云主机类型" prop="cloudType">
        <el-select v-model="submitData.cloudType" placeholder="请选择" clearable @change="cloudTypeChangeHandle">
          <el-option
            v-for="item in cloudTypeOpt"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="CPU信息" prop="cpu">
        <el-input v-model.trim="submitData.cpu" type="textarea" :autosize="{minRows: 2}"/>
      </el-form-item>

      <el-form-item label="计算机核心数" prop="core">
        <el-input-number v-model="submitData.core" :min="null" :max="100" label="CPU核心数"></el-input-number>
        <span>&nbsp;&nbsp;单位：核</span>
      </el-form-item>

      <el-form-item label="计算机内存大小" prop="memory">
        <el-input-number v-model="submitData.memory" :min="null" :max="500" ></el-input-number>
        <span>&nbsp;&nbsp;内存单位：G</span>
      </el-form-item>

      <el-form-item label="磁盘说明" prop="disk">
        <el-input v-model.trim="submitData.disk" type="textarea" :autosize="{minRows: 2}"/>
      </el-form-item>

      <el-form-item label="接入网络兆数(上行)" prop="accessNetworkSizeUp">
          <el-input-number v-model="submitData.accessNetworkSizeUp" :min="null" :max="2000"></el-input-number>
          <span>&nbsp;&nbsp;单位：兆</span>
      </el-form-item>

      <el-form-item label="接入网络兆数(下行)" prop="accessNetworkSizeDown">
          <el-input-number v-model="submitData.accessNetworkSizeDown" :min="null" :max="2000"></el-input-number>
          <span>&nbsp;&nbsp;单位：兆</span>
      </el-form-item>

        <el-form-item label="访问登录信息" prop="access1">
            <!--<el-input v-model="submitData.access1" placeholder="访问登录信息1（管理员级别）" type="textarea" :autosize="{minRows: 3}"/>-->
          <mavon-editor v-model="submitData.access1" :toolbars="toolbars"
                        ref="access1Ref" @imgAdd="imgAddAccess1" @imgDel="imgDel" />
        </el-form-item>

        <!--<el-form-item label="访问登录信息2" prop="access2">-->
        <!--    <el-input v-model="submitData.access2" placeholder="访问登录信息2（普通授权）" type="textarea" :autosize="{minRows: 3}"/>-->
        <!--</el-form-item>-->

        <!--<el-form-item label="访问登录信息3" prop="access3">-->
        <!--    <el-input v-model="submitData.access3" placeholder="访问登录信息3（普通授权）" type="textarea" :autosize="{minRows: 3}"/>-->
        <!--</el-form-item>-->

      <el-form-item label="详情说明" prop="description">
        <el-input v-model.trim="submitData.description" type="textarea" :autosize="{minRows: 3}" />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="toSaveUpd"
                 v-if="defaultValue.saveUpdSelect !== 'select'">{{ defaultValue.title }}</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>


</template>

<script>

import http from '@/utils/http'
import {clearInvalid, checkNull, getUploadImagePath} from "@/utils/utils"

export default {
  name: "OpsComputerServerSaveUpd",
  data() {
    return {
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        close: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '查看',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'select'
      },
      // 提交的数据
      submitData:{
        siteId: null,
        name: null,
        ips: null,
        access1: null,
        access2: null,
        access3: null,
        cloudType: null,
        vm: null,
        cpu: null,
        core: null,
        memory: null,
        disk: null,
        accessNetworkSizeUp: null,
        accessNetworkSizeDown: null,
        parentId: null,
        parentIds: null,
        hostName: null,
        special: null,
        useStatus: null,
        storageLocation: null,
        os: null,
        osVersion: null,
        linchpin: null,
        description: null,
      },
      // 工具类显示的东西 md 插件工具栏配置。下面的去掉一个就会少一个功能
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      // 校验规则
      checkRule: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        vm: [{required: true, message: '请选择是否虚拟机', trigger: 'change'}],
        special: [{required: true, message: '请选择是否特殊主机', trigger: 'change'}],
        useStatus: [{required: true, message: '请选择是否使用', trigger: 'change'}],
        os: [{required: true, message: '请选择系统类型', trigger: 'change'}],
        storageLocation: [{required: true, message: '请输入存在位置', trigger: 'blur'}],
        osVersion: [{required: true, message: '请输入系统版本', trigger: 'blur'}],
      },
      // 云主机类型
      cloudTypeOpt: [
        {code: '', name: ''},
      ],
      // 特殊机器类型
      computerSpecialOpt: [
        {code: '', name: ''},
      ],
      // 计算机类型
      osOpt:[
        {key: 1, value: 'linux'},
        {key: 2, value: 'windows'},
        {key: 3, value: 'mac'},
        {key: 4, value: 'unix'},
        {key: 5, value: '银河麒麟'},
        {key: 6, value: '统信UOS'},
        {key: 7, value: '深度Deepin'},
        {key: 8, value: '华为欧拉'},
        {key: 10, value: '中兴新支点'},
        {key: 11, value: '红旗'},
        {key: 12, value: '华为鸿蒙HarmonyOS'},
        {key: 13, value: '中标麒麟'},
        {key: 9, value: '其他'},
      ],
      // 被选中的计算机
      selectComputer: {name: ''},
      // 当前时间
      dateTime: {
        // 年月日 yyyy-MM-dd
        now: null,
        // 年部分 yyyy
        year: null,
        // 月部分 MM
        month: null,
      },
    }
  },
  methods: {
    /**
     * 获取当前时间
     */
    getTime() {
      http.get("/open/getTime", {}).then(response => {
        // yyyy-MM-dd HH:mm:ss
        let res = response.data;
        this.dateTime.now = res.data
        const date = new Date(this.dateTime.now)
        this.dateTime.year = date.getFullYear()
        // 月份从 0 开始，所以要 +1,提取月份（0-11 → 补零成 01-12）
        this.dateTime.month = (date.getMonth() + 1).toString().padStart(2, '0')

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片删除被触发
     * 这里的删除需要触发标签上面的删除才触发这个删除
     * @param pos 数组0 是文件序号1， 数组1 ，文件
     */
    imgDel(pos){
      // console.log(pos[0])
      // 图片是一个数组，那么这里直接通过pos[0]取出文件路径。
      http.post("/fileStorage/delImageByUrl", {
        url: pos[0],
      }).then(response => {
        let res = response.data;
        this.$message.success("删除成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * md的图片新增被触发
     * @param pos 这里的pos就是图片的信息,示例 1 - 2 -3
     * @param file 上传的文件
     */
    imgAddAccess1(pos, file){
      let formData = new FormData()
      formData.append("file", file)
      formData.append("objectType", "6")
      formData.append("imageTypePath", "access/" + this.dateTime.year + "/" + this.dateTime.month)

      http.postFileForm("/fileStorage/uploadImage", formData).then(response => {
        let res = response.data;
        // 替换在markerDown中的图片路径
        // this.$refs[ref].$img2Url(pos, getUploadImagePath(res.data.id));  动态替换
        this.$refs.access1Ref.$img2Url(pos, getUploadImagePath(res.data.id))
        this.$message.success("上传图片成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 是否虚拟机被选择，发生了改变
     * @param value
     */
    selectVm(value){
      if (value === '0'){
        // 只有选择了物理机才进行验证
        if (!checkNull(this.submitData.cloudType)){
          this.$message.error("已选中云主机，不应该选择物理机");
          this.submitData.vm = 1
          return
        }
        if (this.submitData.parentId === '-1'){
          this.submitData.vm = 0
        } else {
          this.$message.error("当前机器只可能属于虚拟机，不可能存在物理机中的物理机");
          this.submitData.vm = 1
          return
        }
      }
    },
    /**
     * 云主机类型 选择发生变化的时候
     * @param value 选择的主机类型
     */
    cloudTypeChangeHandle(value){
      if (checkNull(value)){
        this.submitData.vm = 0
      } else {
        this.submitData.vm = 1
      }
    },
    /**
     * 初始化操作
     * @param operateType 操作类型,保存还是修改or查看,取值有 select \ save \ upd
     * @param obj 如果是修改和查看，则是详细数据,需要赋值
     * @param selectComputer 被选中的计算机
     */
    init(operateType, obj, selectComputer){
      if (operateType){
        this.defaultValue.saveUpdSelect = operateType
      } else {
        this.defaultValue.saveUpdSelect = "save"
      }
      this.clearOldData()
      this.getCloudType()
      this.getComputerSpecial()
      this.submitData.siteId = this.$route.query.siteId
      this.getTime()

      if (operateType === 'save'){
        this.selectComputer = selectComputer
        this.defaultValue.title = '新增'
        this.submitData.linchpin = 0
        this.submitData.useStatus = 1
        this.submitData.special = 0
        this.submitData.vm = 1
        this.submitData.osVersion = "未知"
        this.submitData.os = 1
        this.submitData.osVersion = "未知"

        if (checkNull(selectComputer) || checkNull(selectComputer.id)){
          this.submitData.parentId = '-1'
          this.submitData.storageLocation = "机房"
        } else {
          this.submitData.parentId = selectComputer.id
          this.submitData.storageLocation = selectComputer.storageLocation
        }

      } else if (operateType === 'upd'){
        if (obj.parentId === '-1'){
          this.selectComputer.name = '当前顶级节点，无父级'
        } else {
          this.selectComputer.name = obj.parentName
        }
        this.defaultValue.title = '修改'
        // 要json处理下，否则会影响之前的值
        this.submitData = JSON.parse(JSON.stringify(obj))

      } else {
        // 可能查看
      }

      this.tableConfig.show = true
    },
    /**
     * 清理掉旧数据
     */
    clearOldData(){
      this.submitData = {
        siteId: null,
        name: null,
        ips: null,
        access1: '',
        access2: null,
        access3: null,
        cloudType: null,
        vm: null,
        cpu: null,
        core: null,
        memory: null,
        disk: null,
        accessNetworkSizeUp: null,
        accessNetworkSizeDown: null,
        parentId: null,
        parentIds: null,
        hostName: null,
        special: null,
        useStatus: null,
        storageLocation: null,
        os: null,
        osVersion: null,
        linchpin: null,
        description: null,
      }
    },
    /**
     * 是保存还是修改
     */
    toSaveUpd(){
      if (this.defaultValue.saveUpdSelect === 'save'){
        this.saveOpsComputerServer()

      } else if (this.defaultValue.saveUpdSelect === 'upd'){
        this.updOpsComputerServer()

      } else {

      }
    },
    /**
     * 获取云主机类型
     */
    getCloudType(){
      http.post("/computer/getCloudType", null).then(response => {
        let res = response.data;
        this.cloudTypeOpt = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 获取特殊机器类型
     */
    getComputerSpecial(){
      http.post("/computer/getComputerSpecial", null).then(response => {
        let res = response.data;
        this.computerSpecialOpt = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 保存
     */
    saveOpsComputerServer(){
      http.post("/computer/saveComputerServer", this.submitData).then(response => {
        let res = response.data;
        this.$message.success("保存成功");
        this.$emit('getComputerServerTree', null)
        // 关闭弹出框,继续添加
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 更新
     */
    updOpsComputerServer(){
      clearInvalid(this.submitData)
      http.post("/computer/updComputerServer", this.submitData).then(response => {
        let res = response.data;
        this.$message.success("更新成功");
        this.$emit('getComputerServerTree', null)
        // 关闭弹出框
        this.tableConfig.show = false

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
  },
  // 进入马上执行
  mounted() {

  },
}
</script>

<style scoped>

</style>

